package de.pixel83.piecemaster.ai;

import java.util.ArrayList;

import de.pixel83.piecemaster.Board;
import de.pixel83.piecemaster.Move;
import de.pixel83.piecemaster.Square;


public class NotSoRandomLoserAi implements Ai{

	private int p = 100;
	private int n = 300;
	private int b = 350; // eindeutig erhöhen
	private int r = 500;
	private int q = 1000;
	private int k = 10000;

	public String getName() {
		return "NotSoRandomLoserAi";
	}

	public Move draw(Board board, char color) {
		Square start = null;
		Move move = null;

		ArrayList<Move> legalMoves = new ArrayList<Move>();
		ArrayList<Square> ownPieces = getAllPieces(board, color);
		for (Square square : ownPieces) {
			legalMoves.addAll(board.getLegalMoves(square));
		}

		int bestRating = 1000000;
		Move bestMove = null;
		for (Move mov : legalMoves) {
			Board tempBoard = new Board(board.toString());
			tempBoard.move(mov);
			int rating = rateBoard(tempBoard, color);
			if (bestMove == null || rating < bestRating) {
				bestRating = rating;
				bestMove = mov;
			}
		}
		System.out.println("##################### Move " + bestMove.toString()
				+ " has " + bestRating);
		return bestMove;
	}

	private ArrayList<Square> getAllPieces(Board board, char color) {
		ArrayList<Square> list = new ArrayList<Square>();
		for (int r = 0; r < 6; r++) {
			for (int c = 0; c < 5; c++) {
				if (board.getColor(board.getPieceAt(r, c)) == color) {
					list.add(new Square(c, r));
				}
			}
		}
		return list;
	}

	private int rateBoard(Board board, char color) {
		int rating = 0;
		for (int r = 0; r < 6; r++) {
			for (int c = 0; c < 5; c++) {
				rating += getValue(board, r, c, color);
			}
		}
		return rating;
	}

	private int getValue(Board board, int row, int col, char color) {
		int value = 0;
		char piece = board.getPieceAt(row, col);
		char originalPice = piece;
		int factor = (Board.getColor(piece) == color ? 1 : -1);
		piece = Character.toLowerCase(piece);
		switch (piece) {
		case 'p':
			value = p;
			break;
		case 'n':
			value = n;
			break;
		case 'b':
			value = b;
			break;
		case 'r':
			value = r;
			break;
		case 'q':
			value = q;
			break;
		case 'k':
			value = k;
			break;
		}
		value = value * factor;
		return value;
	}

	/**
	 * Tests the class RandomAi
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		Board board = new Board();
		Ai ai = new NotSoRandomAi();
		for (int i = 0; i < 3; i++)
			System.out.println(ai.draw(board, 'W'));
	}

}


